package work

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"seat-service/initialization"
	"seat-service/model/dto"
	"strconv"
	"time"
)

const appid = "wx34197ebba6b471a5"
const secret = "e89e9435f3e3e24f5c11448e1f254f66"
const grant_type = "client_credential"

var AccessToken string
var ExpiresIn = 7200

func PushWX(templateId, page, touser, data, miniprogramState, lang string) error {
	url := "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + AccessToken
	payload := []byte(
		`{"template_id": "` + templateId + "\"," +
			`"page": "` + page + "\"," +
			`"touser": "` + touser + "\"," +
			`"data":` + data + "," +
			`"miniprogram_state": "` + miniprogramState + "\"," +
			`"lang": "` + lang + `"}`)
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	if err != nil {
		return err
	}
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return err
	}
	res := dto.ReceiveErr{}
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}
	fmt.Println("code:" + strconv.Itoa(res.ErrCode) + ",msg:" + res.ErrMsg)
	return nil
}

func InitFormat(data map[string]string) string {
	res := `{`
	for s, s2 := range data {
		res = res + `"` + s + `":{"value":` + "\"" + s2 + "\"" + "},"
	}
	res = res[:len(res)-1] + "}"
	return res
}

func Task() {
	time.Sleep(time.Second)
	ticker := time.Tick(time.Duration(ExpiresIn) * time.Second)
	// 无限循环，定时器触发时执行任务
	for {
		select {
		case <-ticker:
			// 在这里执行你的任务
			err := GetTokenWX()
			if err != nil {
				initialization.SeatLogger.Error("获取token失败," + err.Error())
			}
		}
	}
}

func GetTokenWX() error {
	url := "https://api.weixin.qq.com/cgi-bin/token"
	url2 := "?" + "grant_type=" + grant_type + "&" + "appid=" + appid + "&" + "secret=" + secret
	response, err := http.Get(url + url2)
	if err != nil {
		return err
	}
	body := response.Body
	all, err := io.ReadAll(body)
	if err != nil {
		return err
	}
	res := dto.ObtainToken{}
	err = json.Unmarshal(all, &res)
	if err != nil {
		return err
	}
	AccessToken = res.AccessToken
	ExpiresIn = res.ExpiresIn
	return nil
}
